// 登录状态管理工具
class AuthManager {
  constructor() {
    this.loginCallbacks = []
    this.logoutCallbacks = []
  }

  /**
   * 检查登录状态
   */
  isLoggedIn() {
    const userInfo = wx.getStorageSync('userInfo')
    const isLoggedIn = wx.getStorageSync('isLoggedIn')
    return !!(isLoggedIn && userInfo && userInfo._openid)
  }

  /**
   * 获取用户信息
   */
  getUserInfo() {
    if (this.isLoggedIn()) {
      return wx.getStorageSync('userInfo')
    }
    return null
  }

  /**
   * 设置用户信息
   */
  setUserInfo(userInfo) {
    wx.setStorageSync('userInfo', userInfo)
    wx.setStorageSync('isLoggedIn', true)
    this.triggerLoginCallbacks(userInfo)
  }

  /**
   * 清除用户信息
   */
  clearUserInfo() {
    wx.removeStorageSync('userInfo')
    wx.removeStorageSync('isLoggedIn')
    this.triggerLogoutCallbacks()
  }

  /**
   * 检查登录状态，未登录则跳转到登录页
   */
  checkLogin(options = {}) {
    if (!this.isLoggedIn()) {
      const { showToast = true, toastText = '请先登录' } = options
      
      if (showToast) {
        wx.showToast({
          title: toastText,
          icon: 'none',
          duration: 1500
        })
      }

      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/index'
        })
      }, showToast ? 1500 : 0)
      
      return false
    }
    return true
  }

  /**
   * 注册登录回调
   */
  onLogin(callback) {
    if (typeof callback === 'function') {
      this.loginCallbacks.push(callback)
    }
  }

  /**
   * 注册登出回调
   */
  onLogout(callback) {
    if (typeof callback === 'function') {
      this.logoutCallbacks.push(callback)
    }
  }

  /**
   * 触发登录回调
   */
  triggerLoginCallbacks(userInfo) {
    this.loginCallbacks.forEach(callback => {
      try {
        callback(userInfo)
      } catch (error) {
        console.error('登录回调执行失败:', error)
      }
    })
  }

  /**
   * 触发登出回调
   */
  triggerLogoutCallbacks() {
    this.logoutCallbacks.forEach(callback => {
      try {
        callback()
      } catch (error) {
        console.error('登出回调执行失败:', error)
      }
    })
  }

  /**
   * 登出
   */
  logout() {
    return new Promise((resolve) => {
      wx.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            this.clearUserInfo()
            wx.showToast({
              title: '已退出登录',
              icon: 'success'
            })
            resolve(true)
          } else {
            resolve(false)
          }
        }
      })
    })
  }
}

// 创建全局实例
const authManager = new AuthManager()

module.exports = authManager